package com.now.printer.ui.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.android.material.snackbar.Snackbar;
import com.now.printer.R;
import com.now.printer.adapter.SelectAdapter;
import com.now.printer.adapter.TemplateListAdapter;
import com.now.printer.base.BaseActivity2;
import com.now.printer.layout.straight.StraightLayoutHelper;
import com.now.printer.utils.Callback;
import com.now.printer.utils.ConvertUtils;
import com.now.printer.utils.FileUtils2;
import com.now.printer.utils.PrinterUtils;
import com.now.printer.utils.PuzzleUtils;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.xiaopo.flying.puzzle.PuzzleLayout;
import com.xiaopo.flying.puzzle.PuzzlePiece;
import com.xiaopo.flying.puzzle.PuzzleView;
import com.xiaopo.flying.puzzle.SquarePuzzleView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.xutils.common.util.LogUtil;

/**
 *
 * 拼图
 * Created by xudong on 2021/6/8.
 */

public class ProcessActivity extends BaseActivity2 {
    private RelativeLayout rlTop;
    private ImageView imgToBack;
    private TextView imgHelp;
    private TextView tvTitle;
    private RecyclerView templateList;
    private LinearLayout contentProcess;
    private SquarePuzzleView puzzleView;
    private TemplateListAdapter templateListAdapter;

    private static final int FLAG_CONTROL_LINE_SIZE = 1;
    private static final int FLAG_CONTROL_CORNER = 1 << 1;

    private PuzzleLayout puzzleLayout;
    private List<String> bitmapPaint;

    private List<Target> targets = new ArrayList<>();
    private int deviceWidth = 0;

    private int controlFlag;
    private int type;
    private int pieceSize;
    private int themeId;

    @Override
    public int getLayoutId() {
        return R.layout.activity_process;
    }

    @Override
    public void doBusiness(Context mContext) {

        rlTop = (RelativeLayout) findViewById(R.id.rl_top);
        imgToBack = (ImageView) findViewById(R.id.img_toBack);
        imgHelp = (TextView) findViewById(R.id.imgHelp);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        templateList = (RecyclerView) findViewById(R.id.template_list);
        contentProcess = (LinearLayout) findViewById(R.id.content_process);
        puzzleView = (SquarePuzzleView) findViewById(R.id.puzzle_view);


        deviceWidth = getResources().getDisplayMetrics().widthPixels;

        type = getIntent().getIntExtra("type", 0);
        pieceSize = getIntent().getIntExtra("piece_size", 0);
        themeId = getIntent().getIntExtra("theme_id", 0);
        bitmapPaint = getIntent().getStringArrayListExtra("photo_path");
        puzzleLayout = PuzzleUtils.getPuzzleLayout(type, pieceSize, themeId);

        initView();

        puzzleView.post(new Runnable() {
            @Override
            public void run() {
                loadPhoto();
            }
        });
    }


    private void loadPhoto() {
        if (bitmapPaint == null) {
            return;
        }

        final List<Bitmap> pieces = new ArrayList<>();

        final int count = bitmapPaint.size() > puzzleLayout.getAreaCount() ? puzzleLayout.getAreaCount()
                : bitmapPaint.size();

        for (int i = 0; i < count; i++) {
            final Target target = new Target() {
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                    pieces.add(bitmap);
                    if (pieces.size() == count) {
                        if (bitmapPaint.size() < puzzleLayout.getAreaCount()) {
                            for (int i = 0; i < puzzleLayout.getAreaCount(); i++) {
                                puzzleView.addPiece(pieces.get(i % count));
                            }
                        } else {
                            puzzleView.addPieces(pieces);
                        }
                    }
                    targets.remove(this);
                }

                @Override
                public void onBitmapFailed(Drawable errorDrawable) {

                }

                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {

                }
            };

            Picasso.with(this)
                    .load("file:///" + bitmapPaint.get(i))
                    .resize(deviceWidth, deviceWidth)
                    .centerInside()
                    .config(Bitmap.Config.RGB_565)
                    .into(target);

            targets.add(target);
        }
    }


    private void initView() {
        imgToBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });


        puzzleView = (SquarePuzzleView) findViewById(R.id.puzzle_view);

        //TODO the method we can use to change the puzzle view's properties
        puzzleView.setPuzzleLayout(puzzleLayout);
        puzzleView.setTouchEnable(true);
        puzzleView.setNeedDrawLine(false);
        puzzleView.setNeedDrawOuterLine(false);
        puzzleView.setLineSize(4);
        puzzleView.setLineColor(Color.BLACK);
        puzzleView.setSelectedLineColor(Color.BLACK);
        puzzleView.setHandleBarColor(Color.BLACK);
        puzzleView.setAnimateDuration(300);
        puzzleView.setOnPieceSelectedListener(new PuzzleView.OnPieceSelectedListener() {
            @Override
            public void onPieceSelected(PuzzlePiece piece, int position) {
                Snackbar.make(puzzleView, "Piece " + position + " selected", Snackbar.LENGTH_SHORT).show();
            }
        });

        // currently the SlantPuzzleLayout do not support padding
        puzzleView.setPiecePadding(10);

        imgHelp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                File file = FileUtils2.getNewFile(ProcessActivity.this, "Puzzle");
                FileUtils2.savePuzzle(puzzleView, file, 100, new Callback() {
                    @Override
                    public void onSuccess() {
//                        Snackbar.make(view, R.string.prompt_save_success, Snackbar.LENGTH_SHORT).show();
                        assert file != null;
                        String imagePath = file.getPath();
                        String outputPath = imagePath + ".pdf";
                        LogUtil.i("当前文件路径是：" + outputPath);
                        ConvertUtils.convertImageToPdf(ProcessActivity.this,imagePath,outputPath);

                        PrinterUtils.doPrint(ProcessActivity.this,outputPath);
                    }

                    @Override
                    public void onFailed() {
                        Snackbar.make(view, R.string.prompt_save_failed, Snackbar.LENGTH_SHORT).show();
                    }
                });
            }
        });

        templateListAdapter = new TemplateListAdapter();
        templateList.setAdapter(templateListAdapter);
        templateList.setLayoutManager(
                new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        templateList.setHasFixedSize(true);
        templateListAdapter.refreshData(StraightLayoutHelper.getAllThemeLayout(bitmapPaint.size()), bitmapPaint);
        templateListAdapter.setOnItemClickListener(new TemplateListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(PuzzleLayout puzzleLayout2, int themeId) {
                puzzleLayout = PuzzleUtils.getPuzzleLayout(type, pieceSize, themeId);
                initView();
                puzzleView.post(new Runnable() {
                    @Override
                    public void run() {
                        loadPhoto();
                    }
                });
            }
        });
    }
}
